const fileToDataUrl = (s: File) => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      resolve(reader.result);
    });
    reader.readAsDataURL(s);
  });
};

const getSizeRadio = (s: File | string) => {
  return new Promise(async (resolve) => {
    let sourceStr = s as string;
    if (typeof s !== "string") {
      sourceStr = await fileToDataUrl(s);
    }

    const img = new Image();
    img.src = sourceStr;
    img.setAttribute("crossOrigin",'Anonymous')
    img.onload = () => {
      resolve([img, img.width, img.height]);
    };
  });
};

const crop = async (
  source: File | string,
  posInfo: {
    top: number;
    left: number;
    width: number;
    height: number;
  }
) => {
  return new Promise(async (resolve, reject) => {
    const canvas = document.createElement("canvas");
    const [imgEl] = await getSizeRadio(source);
    // canvas.style.position = "absolute";
    // canvas.style.top = "50px";
    // canvas.style.left = "50px";
    // canvas.style.zIndex = "1000";
    canvas.width = posInfo.width;
    canvas.height = posInfo.height;
    // document.body.append(canvas);
    const ctx = canvas.getContext("2d");
    if (!ctx) return "";
    ctx.drawImage(
      imgEl,
      posInfo.left,
      posInfo.top,
      posInfo.width,
      posInfo.height,
      0,
      0,
      posInfo.width,
      posInfo.height
    );
    canvas.toBlob((blob) => {
      resolve(blob);
    });
  });
};

export default crop;
